"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig")
const AuthException = require('../../exception/authException');

class JwtService extends Service {
  // 生成token
  async createToken(userId) {
    try {
      const { app } = this;
      return app.jwt.sign(
        {
          userId: userId,
        },
        app.config.jwt.secret
      );
    } catch (error) {
      this.ctx.logger.info(error);
    }
  }

  // 验证token
  async verifyToken(token) {
    try {
      // 暂时注释
      if (!token) { // 如果token不存在就抛出异常
        throw new AuthException();
      }
      const { app } = this;
      const secret = app.config.jwt.secret;
      try {
        await app.jwt.verify(token, secret);
      } catch (e) {
        // 如果token验证失败直接抛出异常
        // 通过消息判断token是否过期
        if (e.message === 'jwt expired') {
          throw new AuthException('令牌过期', httpCode.LOGINEXPIREERROR);
        }
        throw new AuthException('令牌无效...');
      }
      return true;
    } catch (error) {
      this.ctx.logger.info(error);
    }
  }

  // 通过token获取用户信息
  async getUserInfoFromToken(token) {
    try {
      const { app } = this;
      await this.verifyToken(token);
      // 解析token
      const res = await app.jwt.decode(token);
      return res.userId;
    } catch (error) {
      this.ctx.logger.info(error);
    }

  }
}

module.exports = JwtService;
